﻿Imports System
Imports System.Globalization
Imports System.Security.Principal
Imports System.Web.Mvc
Imports System.Web.Security
Imports Ext.Net
Imports Ext.Net.MVC

Namespace DailyReport
    Public Class AccountController
        Inherits ControllerBase


        ' GET: /Account

        Function Login() As ActionResult
            Dim lm As New LoginModel With {.Username = Now.ToString("dd HH:MM:ss")}

            'Dim ul As New List(Of User)
            'Using re As New DailyReportEntitiesEX
            '    Dim abc = From c In re.User Select c
            '    Debug.Print("")
            'End Using

            'Debug.Print("")
            'FormsAuthentication.GetAuthCookie(

            Return View(lm)
        End Function

        Function LogOut() As ActionResult
            FormsAuthentication.SignOut()
            Return RedirectToAction("Login", "Account")
        End Function

        <HttpPost()>
        Function Login(ByVal args As LoginModel, ByVal returnUrl As String) As ActionResult
            If ModelState.IsValid Then
                Dim u As User = ValidateLogOn(args.Username, args.Password)
                If Not String.IsNullOrEmpty(u.id) Then
                    FormsAuthentication.SetAuthCookie(String.Concat(u.id, "|", u.username, "|", u.number, "|", u.departmentid, "|", u.permissions), True)
                    HttpContext.Cache("DR_CurrentUser") = u
                    'Dim ticket As New FormsAuthenticationTicket(1, u.username, Now, Now.AddMinutes(60), True, String.Concat(u.id, "|", u.username, "|", u.number))
                    'Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
                    'Dim cookie2 As New HttpCookie("dr_user", String.Concat(u.id, "|", u.username, "|", u.number))
                    'Response.Cookies.Add(cookie)
                    'Response.Cookies.Add(cookie2)

                    If Not String.IsNullOrEmpty(returnUrl) Then
                        Return Redirect(returnUrl)
                    Else
                        Return RedirectToAction("Index", "Home")
                    End If
                Else
                    Return New AjaxResult With {.ErrorMessage = "错误的用户名或密码！"}
                End If
            End If
            Return View(args)
        End Function

        Private Function ValidateLogOn(ByVal userName As String, ByVal password As String) As User

            Dim ul As New List(Of User)
            Dim u As User
            Using re As New DailyReportEntitiesEX
                Dim result = From c In re.User
                             Where c.username = userName And c.password = c.password Or c.number = userName And c.password = password And c.status = DailyReportCommon.UserStatus.正常
                             Select c
                If result.Count > 0 Then
                    u = result.First()
                    'FormsAuthentication.SetAuthCookie(String.Concat(u.id, "|", u.username, "|", u.number), True)
                    'FormsAuthentication.SetAuthCookie(u, True)

                    u.lastlogintime = Now
                    re.SaveChanges()

                    Return u
                Else
                    Return New User
                End If
            End Using
        End Function

        Function UserList() As ActionResult
            Return View()
        End Function

        Function ChangePassword() As ActionResult
            ViewData("UserID") = CurrentUserID

            Return View()
        End Function

        Public Function GetUserStore() As AjaxStoreResult
            Try
                Dim ul As List(Of User)
                Using re As New DailyReportEntitiesEX
                    ul = (From c In re.User
                          Where c.isbuildin = 0
                          Select c).ToList
                End Using

                Return New AjaxStoreResult(ul, ul.Count)
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function SaveUsesrWithConfirmation() As AjaxStoreResult
            Dim ajaxStoreResult As New AjaxStoreResult(StoreResponseFormat.Save)
            Try
                Dim dataHandler = New StoreDataHandler(HttpContext.Request("data"))
                Dim data As ChangeRecords(Of User) = dataHandler.ObjectData(Of User)()
                Dim confirmationList As ConfirmationList = dataHandler.BuildConfirmationList("username")

                For Each dc In data.Created
                    Using re As New DailyReportEntitiesEX
                        Dim nu As New User With {.id = System.Guid.NewGuid.ToString(),
                                                .username = dc.username,
                                                .password = dc.number,
                                                .number = dc.number,
                                                .sex = dc.sex
                            }
                        re.User.AddObject(nu)
                        re.SaveChanges()
                    End Using
                Next

                For Each du In data.Updated
                    Using re As New DailyReportEntitiesEX
                        'Dim oal = (From c In re.User
                        '                    Where c.id = du.id
                        '                    Select c)
                        Dim ou As User = (From c In re.User
                                            Where c.id = du.id
                                            Select c).First
                        'If oal.Count > 0 Then
                        '    ou = oal.First
                        ou.username = du.username
                        ou.number = du.number
                        ou.sex = du.sex
                        ou.status = du.status
                        re.SaveChanges()
                        'End If
                    End Using
                Next

                For Each dd In data.Deleted
                    'Using re As New DailyReportEntitiesEX
                    '    re.Assess.DeleteObject(dd)
                    '    'todo:删除有bug
                    '    re.SaveChanges()
                    'End Using
                Next

                For Each c In confirmationList
                    confirmationList(c.Key).ConfirmRecord()
                Next

                ajaxStoreResult.SaveResponse.ConfirmationList = confirmationList
            Catch ex As Exception
                ajaxStoreResult.SaveResponse.Success = False
                ajaxStoreResult.SaveResponse.Message = ex.Message
            End Try

            Return ajaxStoreResult
        End Function

        Function SavePermissions(userid As String, permissions As Integer) As ActionResult
            Try
                Using re As New DailyReportEntitiesEX
                    Dim ou As User = (From c In re.User
                                            Where c.id = userid
                                            Select c).First
                    ou.permissions = permissions
                    re.SaveChanges()
                End Using
                Return Content("Success")
            Catch ex As Exception
                Return Content("Error")
            End Try
        End Function

        Function SavePassword(userid As String, oldpassword As String, newpassword As String) As ActionResult
            Try
                Dim ou As User
                Dim done As Boolean = False
                Using re As New DailyReportEntitiesEX
                    Dim tou = (From c In re.User
                                            Where c.id = userid And c.password = oldpassword
                                            Select c)
                    If tou.Count > 0 Then
                        ou = tou.First
                        ou.password = newpassword
                        re.SaveChanges()
                        done = True
                    Else
                        done = False
                    End If
                End Using

                If done Then
                    Return Content("Success")
                Else
                    Return Content("用户密码错！")
                End If
            Catch ex As Exception
                Return Content("Error")

            End Try
        End Function

        Function SetPermissions(userid As String) As ActionResult
            Dim up As Integer = 0
            Dim pl As New List(Of Integer)
            Dim ps As String = ""
            Try
                Using re As New DailyReportEntitiesEX
                    Dim ou As User = (From c In re.User
                                            Where c.id = userid
                                            Select c).First
                    up = ou.permissions
                End Using
                pl = DailyReportCommon.GetPermissionList(up)
                For Each p In pl
                    ps += String.Concat(p.ToString, ",")
                Next
                ps = ps.Substring(0, ps.Length - 1)
            Catch ex As Exception

            End Try
            ViewData("UserID") = userid
            ViewData("TotalPermission") = up
            ViewData("Permissions") = ps
            Return View()
        End Function
    End Class

End Namespace